package com.shop.servlet.cart;

import java.io.IOException

;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shop.cart.Cart;
import com.shop.entity.Product;
import com.shop.service.ProductService;

/**
 * Servlet implementation class CartServlet
 */
@WebServlet("/cart")
public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CartServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = "";

		int id = Integer.parseInt(request.getParameter("productId"));
		ProductService ps = new ProductService();
		Product p = ps.findProductById(id);
		HttpSession session = request.getSession();

		Cart c = (Cart) session.getAttribute("cart");
		if (c == null) {
			c = new Cart();
		}
		c.addCartItem(p);
		if (id > 0) {
			msg = "添加成功,商品在购物车等您噢！";
			request.setAttribute("msg", msg);
			session.setAttribute("cart", c);
			request.getRequestDispatcher("productlist").forward(request, response);
		} else {
			msg = "添加失败";
			request.setAttribute("msg", msg);
			session.setAttribute("cart", c);
			request.getRequestDispatcher("productlist").forward(request, response);

		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
